package dz.webcom.formation.webservice;

import java.io.IOException;
import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.ResultReceiver;

public class MyAsyncTask extends AsyncTask<Object, Void, Object> {

	ResultReceiver rc;

	@Override
	protected void onPostExecute(final Object json) {
		MyResult myResult = (MyResult) json;
		Bundle b = new Bundle();
		b.putString("json", myResult.json);
		rc.send(myResult.code, b);
	}

	@Override
	protected Object doInBackground(Object... params) {
		rc = (ResultReceiver) params[1];
		BasicHttpParams httpParams = new BasicHttpParams();
		DefaultHttpClient client = new DefaultHttpClient(httpParams);

		HttpGet request = new HttpGet();
		request.setURI(URI.create((String) params[0]));
		try {

			HttpResponse response = client.execute(request);

			HttpEntity entity = response.getEntity();
			int code = response.getStatusLine().getStatusCode();
			final String json = EntityUtils.toString(entity);

			return new MyResult(code, json);

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	private static class MyResult {

		private int code;
		private String json;

		public MyResult(int code, String json) {
			this.code = code;
			this.json = json;
		}
	}

}